//
//  WlisMeVC.swift
//  Swift_missScarlett
//
//  Created by xmg on 16/8/13.
//  Copyright © 2016年 wlis. All rights reserved.
//

import UIKit
import Alamofire
import MJExtension
import SDWebImage

let cols : CGFloat = 4
let margin : CGFloat = 1.0
/** 设置cell宽高 */
let cellWH = (WlisScreenW - (cols - 1) * margin )/cols

let  MeCellID = "meCellID"

class WlisMeVC: UITableViewController {
    
    
    var squareItems : NSMutableArray?
    var collectionView : UICollectionView?
    override func viewDidLoad() {
        super.viewDidLoad()

        /** 设置导航条 */
        setUpNavBar()

        /** 设置尾部视图 */
        setUpFootView();
        /** 加载数据 */
        loadMeData();
        
    }

  
  

   
  
    
}

// MARK: - 私有方法
private extension WlisMeVC{
    
    /** 设置顶部按钮文字点击 */
    func setUpNavBar(){
        let settingItem = UIBarButtonItem.itemWithCustomView("mine-setting-icon", imageHight: "mine-setting-icon-click", target: self, action:"settingClick")
        
        let nightItem = UIBarButtonItem.itemWithCustomView("mine-moon-icon", imageSelected: "mine-moon-icon-click", target: self, action:"nightClick:")
        
        self.navigationItem.title = "我的"
        
        self.navigationItem.rightBarButtonItems = [settingItem,nightItem]
    }
 
    /** 点击设置 */
    @objc func settingClick(){
        
    }
    /** 设置夜间模式 */
    @objc func nightClick(btn:UIButton){
        btn.selected = !btn.selected
    }
    
    // MARK: - 设置尾部视图
    func setUpFootView(){
    
        /** 创建流水布局 */
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(cellWH, cellWH)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        let collectionView = UICollectionView(frame: CGRectMake(0, 0, 0, 300), collectionViewLayout: layout)
        /** 设置背景 */
        collectionView.backgroundColor = self.tableView.backgroundColor
        /** 设置拖动 */
        collectionView.scrollEnabled = false
        /** 设置数据源 */
        collectionView.dataSource = self;
        /** 设置代理 */
        collectionView.delegate = self
        self.collectionView = collectionView
        self.tableView.tableFooterView = collectionView
        /** 注册cell */
        collectionView.registerNib(UINib(nibName:"WlisSquareCell", bundle: nil), forCellWithReuseIdentifier: MeCellID)
        
    }
 
    /** 加载数据 */
    func loadMeData(){
        /** 创建字典 */
        var parameters = [String : String]();
        parameters["a"] = "square"
        parameters["c"] = "topic"
        Alamofire.request(.GET, "http://api.budejie.com/api/api_open.php", parameters: parameters).responseJSON { (response) -> Void in
            if let JSON = response.result.value{
            
                /** 写文件 */
                (JSON as! NSDictionary).writeToFile("/Users/xmg/Desktop/xmg_UI/xmg_Swift1day/Swift_missScarlett/Swift_missScarlett/Swift_missScarlett/me.plist", atomically: true)
                self.squareItems = WlisSquareItem.mj_objectArrayWithKeyValuesArray(JSON["square_list"])
                /** 设置collectionView高度 */
                self.setUpCollectionView()
                /** 刷新数据 */
                self.collectionView?.reloadData()
               
            }
        }
    }
    /** 设置高度 */
    func setUpCollectionView(){
        let count : Int = (self.squareItems?.count)!
        let rows = (count - 1) / Int(cols) + 1
        self.collectionView?.height = CGFloat(rows) * cellWH
        self.tableView.tableFooterView = self.collectionView
        
        var  extre  = count % Int(cols)
        if extre > 0{
            extre = Int(cols) - extre
            for _ in 1...extre {
            self.squareItems?.addObject(WlisSubTagItem())
            }
        }
    }
}
extension WlisMeVC : UICollectionViewDataSource,UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.squareItems?.count ?? 0 ;
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell : WlisSquareCell = collectionView .dequeueReusableCellWithReuseIdentifier(MeCellID, forIndexPath: indexPath) as! WlisSquareCell
        cell.item = self.squareItems![indexPath.item] as? WlisSquareItem
        
        return cell;
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let item : WlisSquareItem = self.squareItems![indexPath.row] as! WlisSquareItem
        guard let url = NSURL(string: item.url!) else{return}
        
        let webVc = WlisWebVC()
        webVc.url = url
        self.navigationController?.pushViewController(webVc, animated: true)
        
    }
    
}
